import { getAllKeywords, getKeywordType, getDatabaseKeywords } from './sqlKeywords'

/**
 * 自动完成建议项
 * @typedef {Object} Suggestion
 * @property {string} text - 建议文本
 * @property {string} type - 建议类型 (keyword, table, column, function)
 * @property {string} description - 描述
 * @property {number} priority - 优先级 (数字越小优先级越高)
 */

/**
 * 获取自动完成建议
 * @param {string} input - 当前输入
 * @param {number} cursorPosition - 光标位置
 * @param {Object} context - 上下文信息 (tables, columns, dbType等)
 * @returns {Array<Suggestion>} 建议列表
 */
export const getAutocompleteSuggestions = (input, cursorPosition, context = {}) => {
  if (!input || cursorPosition < 0) {
    return []
  }

  const { tables = [], columns = [], dbType = '' } = context
  
  // 获取当前单词
  const currentWord = getCurrentWord(input, cursorPosition)
  
  if (!currentWord || currentWord.length < 2) {
    return []
  }

  const suggestions = []
  
  // 添加关键词建议
  suggestions.push(...getKeywordSuggestions(currentWord, dbType))
  
  // 添加表名建议
  suggestions.push(...getTableSuggestions(currentWord, tables))
  
  // 添加列名建议
  suggestions.push(...getColumnSuggestions(currentWord, columns))
  
  // 添加函数建议
  suggestions.push(...getFunctionSuggestions(currentWord, dbType))
  
  // 按优先级和匹配度排序
  return suggestions
    .sort((a, b) => {
      // 先按优先级排序
      if (a.priority !== b.priority) {
        return a.priority - b.priority
      }
      
      // 再按匹配度排序（完全匹配优先）
      const aExact = a.text.toLowerCase().startsWith(currentWord.toLowerCase())
      const bExact = b.text.toLowerCase().startsWith(currentWord.toLowerCase())
      
      if (aExact && !bExact) return -1
      if (!aExact && bExact) return 1
      
      // 最后按字母顺序排序
      return a.text.localeCompare(b.text)
    })
    .slice(0, 20) // 限制建议数量
}

/**
 * 获取当前光标位置的单词
 */
const getCurrentWord = (input, cursorPosition) => {
  const beforeCursor = input.substring(0, cursorPosition)
  const afterCursor = input.substring(cursorPosition)
  
  // 向前查找单词边界
  const wordStart = beforeCursor.search(/\w+$/)
  const wordStartPos = wordStart === -1 ? cursorPosition : wordStart
  
  // 向后查找单词边界
  const wordEndMatch = afterCursor.match(/^\w*/)
  const wordEnd = wordEndMatch ? wordEndMatch[0].length : 0
  
  const word = input.substring(wordStartPos, cursorPosition + wordEnd)
  
  return word
}

/**
 * 获取关键词建议
 */
const getKeywordSuggestions = (currentWord, dbType = '') => {
  // 根据数据库类型获取关键词
  const keywords = dbType ? getDatabaseKeywords(dbType) : getAllKeywords()
  const suggestions = []
  
  keywords.forEach(keyword => {
    if (keyword.toLowerCase().includes(currentWord.toLowerCase())) {
      const type = getKeywordType(keyword)
      suggestions.push({
        text: keyword,
        type: 'keyword',
        description: `SQL关键词 ${type ? `(${type})` : ''}`,
        priority: 1
      })
    }
  })
  
  return suggestions
}

/**
 * 获取表名建议
 */
const getTableSuggestions = (currentWord, tables) => {
  const suggestions = []
  
  tables.forEach(table => {
    if (table.name && table.name.toLowerCase().includes(currentWord.toLowerCase())) {
      const suggestion = {
        text: table.name,
        type: 'table',
        description: `表 ${table.comment ? `- ${table.comment}` : ''}`,
        priority: 2
      }
      suggestions.push(suggestion)
    }
  })
  
  return suggestions
}

/**
 * 获取列名建议
 */
const getColumnSuggestions = (currentWord, columns) => {
  const suggestions = []
  
  columns.forEach(column => {
    if (column.name && column.name.toLowerCase().includes(currentWord.toLowerCase())) {
      const suggestion = {
        text: column.name,
        type: 'column',
        description: `列 (${column.type}) ${column.comment ? `- ${column.comment}` : ''}`,
        priority: 3
      }
      suggestions.push(suggestion)
    }
  })
  
  return suggestions
}

/**
 * 获取函数建议
 */
const getFunctionSuggestions = (currentWord, dbType = '') => {
  // 通用SQL函数
  const commonFunctions = [
    { name: 'COUNT', description: '计数函数' },
    { name: 'SUM', description: '求和函数' },
    { name: 'AVG', description: '平均值函数' },
    { name: 'MAX', description: '最大值函数' },
    { name: 'MIN', description: '最小值函数' },
    { name: 'CONCAT', description: '字符串连接函数' },
    { name: 'SUBSTRING', description: '字符串截取函数' },
    { name: 'LENGTH', description: '字符串长度函数' },
    { name: 'UPPER', description: '转大写函数' },
    { name: 'LOWER', description: '转小写函数' },
    { name: 'NOW', description: '当前时间函数' },
    { name: 'DATE', description: '日期函数' },
    { name: 'YEAR', description: '年份函数' },
    { name: 'MONTH', description: '月份函数' },
    { name: 'DAY', description: '日期函数' }
  ]
  
  // 数据库特有函数
  let dbSpecificFunctions = []
  
  if (dbType) {
    switch (dbType.toLowerCase()) {
      case 'mysql':
      case 'mariadb':
        dbSpecificFunctions = [
          { name: 'IFNULL', description: '如果为NULL则返回替代值' },
          { name: 'IF', description: '条件函数' },
          { name: 'DATE_FORMAT', description: '日期格式化' },
          { name: 'CURDATE', description: '当前日期' },
          { name: 'DATEDIFF', description: '日期差值' },
          { name: 'TIMESTAMPDIFF', description: '时间差值' },
          { name: 'GROUP_CONCAT', description: '组合字符串' }
        ]
        break
      case 'postgresql':
      case 'postgres':
      case 'pg':
        dbSpecificFunctions = [
          { name: 'TO_CHAR', description: '格式化为字符串' },
          { name: 'TO_DATE', description: '转换为日期' },
          { name: 'TO_TIMESTAMP', description: '转换为时间戳' },
          { name: 'EXTRACT', description: '提取日期部分' },
          { name: 'STRING_AGG', description: '组合字符串' },
          { name: 'ARRAY_AGG', description: '组合为数组' }
        ]
        break
      case 'sqlserver':
      case 'mssql':
      case 'tsql':
        dbSpecificFunctions = [
          { name: 'CONVERT', description: '类型转换' },
          { name: 'DATEADD', description: '日期加减' },
          { name: 'DATEDIFF', description: '日期差值' },
          { name: 'ISNULL', description: 'NULL替换' },
          { name: 'STUFF', description: '替换字符串部分' }
        ]
        break
      case 'oracle':
      case 'plsql':
        dbSpecificFunctions = [
          { name: 'TO_DATE', description: '转换为日期' },
          { name: 'TO_CHAR', description: '格式化为字符串' },
          { name: 'NVL', description: 'NULL替换' },
          { name: 'DECODE', description: '条件判断' },
          { name: 'LISTAGG', description: '组合字符串' }
        ]
        break
      case 'sqlite':
        dbSpecificFunctions = [
          { name: 'STRFTIME', description: '日期格式化' },
          { name: 'DATE', description: '日期函数' },
          { name: 'JULIANDAY', description: '儒略日' },
          { name: 'INSTR', description: '子字符串位置' }
        ]
        break
    }
  }
  
  // 合并通用函数和数据库特有函数
  const allFunctions = [...commonFunctions, ...dbSpecificFunctions]
  
  const suggestions = []
  
  allFunctions.forEach(func => {
    if (func.name.toLowerCase().includes(currentWord.toLowerCase())) {
      suggestions.push({
        text: func.name + '()',
        type: 'function',
        description: func.description,
        priority: 4
      })
    }
  })
  
  return suggestions
}

/**
 * 应用自动完成建议
 * @param {string} input - 原始输入
 * @param {number} cursorPosition - 光标位置
 * @param {Suggestion} suggestion - 选中的建议
 * @returns {Object} 新的输入和光标位置
 */
export const applySuggestion = (input, cursorPosition, suggestion) => {
  const currentWord = getCurrentWord(input, cursorPosition)
  const wordStart = input.substring(0, cursorPosition).lastIndexOf(currentWord)
  const wordEnd = wordStart + currentWord.length
  
  const newInput = input.substring(0, wordStart) + suggestion.text + input.substring(wordEnd)
  const newCursorPosition = wordStart + suggestion.text.length
  
  return {
    input: newInput,
    cursorPosition: newCursorPosition
  }
}

export default {
  getAutocompleteSuggestions,
  applySuggestion
} 